<template>
    <div class="form-wrapper">
        <el-card class="form">
            <h1 class="register-title">用户注册</h1>
            <el-form  ref="form" :model="form" :rules="rules" label-width="80px">
                <el-form-item label="账户" prop="name">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input type="password" v-model="form.password"></el-input>
                </el-form-item>
                <el-form-item label="确认密码" prop="secondPassword">
                    <el-input type="password" v-model="form.secondPassword"></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="register">注册</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script>
import Service from '@/service/request'

export default {
    data() {
        var validateSecondPassword = (rule, value, callback) => {
            if (this.form.password === this.form.secondPassword) {
                callback()
            } else {
                callback(new Error('两次密码输入不一致！'))
            }
        }

        return {
            form: {
                name: '',
                password: '',
                email: ''
            },
            rules: {
                name: [
                    { required: true, message: '请输入账号', trigger: 'blur' },
                ],
                email: [
                    { required: true, message: '请输入邮箱', trigger: 'blur' },
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur'}
                ],
                secondPassword: [
                    { required: true, validator: validateSecondPassword}
                ]
            }
      };
    },
    methods: {
        async register() {
            this.$refs.form.validate(async (valid) => {
                if(valid) {
                    const data = await Service.register(this.form.name, this.form.password, this.form.email)
                    console.log("register >>>", data)
                    this.$message.info('注册成功')
                    this.$router.push('/login')
                }
            })
            
        }
    }
}
</script>

<style>
.register-title {
    margin-bottom: 20px;
}
.form-wrapper {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
}

.form {
    width: 500px;
    height: 400px;
    position: absolute;
    top: 30%;
    left: calc(50% - 250px);

}

</style>